package app.dtos;

import com.google.common.collect.Maps;

import java.util.*;

/**
 * <p>
 * .
 * </p>
 *
 * @author Jerry Ou
 * @version 1.0 2014-04-27 13:04
 * @since JDK 1.6
 */
public class Shake {


    private class TreeMapSorted implements Comparator<Map.Entry<String, Integer>> {
        @Override
        public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
            return o2.getValue() - o1.getValue();
        }
    }


    public boolean started = false;

    public Map<String, Integer> map = Maps.newHashMap();

    private final  static Shake me = new Shake();

    public static Shake me() {
        return me;
    }


    public List<Map.Entry<String,Integer>> sort(Map<String,Integer> map) {
        List<Map.Entry<String,Integer>> list = new ArrayList<Map.Entry<String,Integer>>(map.entrySet());
        Collections.sort(list, new TreeMapSorted());
        return list;
    }

    public List<Map.Entry<String,Integer>> list(int size) {
        List<Map.Entry<String,Integer>> list = sort(map);
        if (list.size() > size) {
            List<Map.Entry<String,Integer>> newList = new ArrayList<Map.Entry<String,Integer>>();
            for (int i=0;i<size;i++) {
                newList.add(list.get(i));
            }
            return newList;
        }
        return list;
    }

    public void start() {
        synchronized (map) {
            map.clear();
            this.started = true;
        }
    }

    public void stop() {
        synchronized (map) {
            //map.clear();
            this.started = false;
        }
    }

    public void shake(String phone) {
        synchronized(map) {
            Integer count = map.get(phone);
            if (count == null) {
                count = 1;
            } else {
                count = count + 1;
            }
            map.put(phone, count);
        }
    }

}
